package com.leyou.auth.interceptors;

import com.leyou.auth.utils.UserContext;
import com.leyou.constants.JwtConstants;
import com.leyou.dto.Payload;
import com.leyou.dto.UserDetails;
import com.leyou.myException.LyException;
import com.leyou.utils.CookieUtils;
import com.leyou.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.rmi.runtime.Log;

import javax.print.attribute.standard.PrinterURI;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jshstart
 * @creat 2020-12-23 20:03
 */
@Slf4j
public class LoginInterceptors implements HandlerInterceptor {
    private JwtUtil jwtUtil;

    public LoginInterceptors(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取用户cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        if (jwt==null){
            throw new LyException(401,"未登录");
        }
        //2.验证jwt，获取用户信息
        Payload payload = jwtUtil.parseJwt(jwt);
        UserDetails userDetail = payload.getUserDetail();
        //3.判断结果，如果匹配就放行
        if (userDetail==null){
            throw new LyException(401,"未登录");
        }
        //4.放行
        log.info("用户{}正在访问",userDetail.getUsername());
        //5.保存用户到userContext中
        UserContext.setUser(userDetail);
        //6.保存jwt到UserContext中
        UserContext.setJwt(jwt);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //当业务结束后，移除用户
        UserContext.removeUser();
    }
}
